<template>
  <div>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchList">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="综合搜索">
                <a-input v-model="queryParam.boxSn" placeholder="请精确输入订单号、手机号、负责人姓名" allowClear />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="会员昵称">
                <a-input v-model="queryParam.nickName" placeholder="请输入会员昵称" allowClear />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="物流单号">
                <a-input v-model="queryParam.expressNo" placeholder="请输入物流单号" allowClear />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="状态">
                <a-select v-model="queryParam.status" placeholder="请选择" :getPopupContainer="triggerNode => triggerNode.parentNode">
                  <a-select-option value="null">全部</a-select-option>
                  <a-select-option :value="item.stateValue" v-for="(item, index) in statusList" :key="index">{{ item.stateName }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="异常警告">
                <a-select v-model="queryParam.isWarn" placeholder="请选择" :getPopupContainer="triggerNode => triggerNode.parentNode">
                  <a-select-option value="null">全部</a-select-option>
                  <a-select-option v-for="item in isWarnList" :value="item.value" :key="item.value">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="创建时间" has-feedback>
                <a-range-picker style="width: 100%" showToday valueFormat="YYYY-MM-DD" format="YYYY-MM-DD" v-model="queryParam.regTime" @change="onChange" @ok="onOk" />
              </a-form-item>
            </a-col>
            <a-col :md="24" :sm="24">
              <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
                <a-button type="primary" @click="searchList">查询</a-button>
                <a-button style="margin-left: 18px" @click="resetList">重置</a-button>
                <!-- <a-popconfirm style="margin-left: 18px" title="确定导出当前条件下的订单?" ok-text="Yes" cancel-text="No" @confirm="confirm" @cancel="cancel">
                  <a-button>导出</a-button>
                </a-popconfirm> -->
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <s-table ref="table" size="default" :rowKey="record => record.id" :columns="columns" :data="loadData" :pagination="paginationProps" :scroll="{ x: 1800 }" :bordered="false">
        <span slot="boxSn" slot-scope="text, record">
          {{ text }}
          <a-tag color="#f50" v-if="record.platForm == 0" style="margin-left: 6px">旧</a-tag><br />
          <a-tag color="pink" style="margin-top: 4px" v-if="record.sourceCode == 1">主题搭配</a-tag>
          <a-tag color="orange" v-if="record.isEb == 1">内淘</a-tag>
        </span>
        <span slot="status" slot-scope="text">{{ text | filterStatus(statusList) }}</span>
        <span slot="placleOrder" slot-scope="text">{{ text | placleOrder }}</span>
        <span slot="purchase" slot-scope="text, record">{{ record.buyCount }}/{{ record.allCount }}</span>
        <span slot="isWarn" slot-scope="text" style="color: #f5222d">{{ text | isWarn }}</span>
        <span slot="action" slot-scope="text, record">
          <template>
            <router-link :to="`/box/serviceOrder/detail/${record.id}`">详情</router-link>
            <a-divider type="vertical" />
            <a-dropdown>
              <a class="ant-dropdown-link">更多<a-icon type="down" /></a>
              <a-menu slot="overlay">
                <a-menu-item v-if="filterAction('物流', record.status)">
                  <a @click="showLogistics(record)">物流</a>
                </a-menu-item>
                <a-menu-item v-if="type == 'fashioner'">
                  <router-link :to="`/box/print/${record.id}`">打印</router-link>
                </a-menu-item>
                <a-menu-item v-if="type == 'fashioner' && filterAction('删款', record.status)">
                  <a @click="showDelete(record)">删款</a>
                </a-menu-item>
                <a-menu-item v-if="type == 'fashioner' && filterAction('补货', record.status)">
                  <a @click="showReplenish(record)">补货</a>
                </a-menu-item>
                <a-menu-item v-if="type == 'fashioner' && filterAction('结算', record.status)">
                  <a @click="showPay(record)">结算</a>
                </a-menu-item>
                <a-menu-item v-if="type == 'fashioner' && filterAction('还货', record.status)">
                  <a @click="showReturn(record)">还货</a>
                </a-menu-item>
                <a-menu-item v-if="type == 'fashioner' && filterAction('还货记录', record.status)">
                  <a @click="showStill(record)">还货记录</a>
                </a-menu-item>
                <a-menu-item v-if="record.buyCount == 0">
                  <a @click="showSpecifySettle(record)">指定结算</a>
                </a-menu-item>
                <a-menu-item v-if="type == 'fashioner' && filterAction('重制', record.status)">
                  <a @click="reMake(record)">重制</a>
                </a-menu-item>

                <!-- <a-menu-item v-if="type == 'fashioner' && filterAction('异常处理', record.status) && record.isWarn == 1">
                  <a @click="showAbnormal(record)">异常处理</a>
                </a-menu-item> -->

                <a-menu-item v-has="'test:send'" v-if="filterAction('测试发货', record.status)">
                  <template>
                    <a @click="showTestDeliver(record)">测试发货</a>
                  </template>
                </a-menu-item>
                <a-menu-item v-has="'test:sign'" v-if="filterAction('测试签收', record.status)">
                  <template>
                    <a @click="showTestSign(record)">测试签收</a>
                  </template>
                </a-menu-item>
                <a-menu-item v-has="'test:finish'" v-if="filterAction('测试完成', record.status)">
                  <template>
                    <a @click="showTestDone(record)">测试完成</a>
                  </template>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </span>
      </s-table>
    </a-card>
    <LogisticsModal ref="logisticsModal"></LogisticsModal>
    <Replenish ref="replenish" @updateTable="updateTable"></Replenish>
    <StillGood ref="stillGood"></StillGood>
    <DeleteGoodsModal ref="deleteGoods"></DeleteGoodsModal>
    <ReturnGoodsModal ref="returnGoods" @updateTable="updateTable"></ReturnGoodsModal>
    <ReturnRecordModal ref="returnRecord"></ReturnRecordModal>
    <CancelModal ref="cancelModal"></CancelModal>
    <ForTestModal ref="forTestModal" @updateTable="updateTable"></ForTestModal>
    <SpecifySettleModal ref="specifySettleModal" @updateTable="updateTable"></SpecifySettleModal>
    <PayModal ref="payModal" @updateTable="updateTable"></PayModal>
  </div>
</template>
<script>
import { STable } from '../components'
import LogisticsModal from './components/logisticsModal.vue'
import Replenish from './components/replenishment'
import StillGood from './components/stillGood'
import DeleteGoodsModal from './components/deleteGoodsModal'
import ReturnGoodsModal from './components/returnGoodsModal'
import ReturnRecordModal from './components/returnRecordModal'
import CancelModal from './components/cancelModal'
import ForTestModal from './components/forTestModal'
import PayModal from './components/payModal'
import { queryForList, boxListCount, getBoxByBoxId, resetAddCartByBoxId, getSupplyLogistics, checkUnSignProduct } from '@/api/box/order'
import SpecifySettleModal from './components/specifySettleModal'
import { getOrderAction, fetchUserIsBlack } from '@/views/box/util/global'
import globalData from '@/views/box/util/global'
import { globalMixin } from '@/views/box/util/globalMixin'
import Vue from 'vue'
import { USER_INFO } from '@/store/mutation-types'
import '@/views/box/util/filter'

const columns = [
  {
    title: '服务单号',
    dataIndex: 'boxSn',
    align: 'left',
    width: '180px',
    scopedSlots: { customRender: 'boxSn' }
  },
  {
    title: '会员昵称',
    dataIndex: 'nickName',
    align: 'center'
  },
  {
    title: '联系方式',
    dataIndex: 'phone',
    align: 'center',
    width: '135px',
    scopedSlots: { customRender: 'phone' }
  },
  {
    title: '状态',
    dataIndex: 'status',
    align: 'center',
    width: '90px',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '异常警告',
    dataIndex: 'isWarn',
    align: 'center',
    width: '90px',
    scopedSlots: { customRender: 'isWarn' }
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    align: 'center',
    width: '120px'
  },
  {
    title: '商品金额',
    dataIndex: 'totalPrice',
    align: 'center',
    customRender: text => '¥ ' + text
  },
  {
    title: '成交金额',
    dataIndex: 'dealMoney',
    align: 'center',
    customRender: text => '¥ ' + text
  },
  {
    title: '购买/商品数',
    align: 'center',
    scopedSlots: { customRender: 'purchase' }
  },
  {
    title: '还货总数',
    dataIndex: 'returnCount',
    align: 'center'
  },
  /*  {
    title: '补货次数',
    dataIndex: 'supplyTimes',
    align: 'center'
  }, */
  {
    title: '补货总数',
    dataIndex: 'supplyCount',
    align: 'center'
  },
  {
    title: '服务单来源',
    dataIndex: 'placleOrder',
    align: 'center',
    width: '105px',
    scopedSlots: { customRender: 'placleOrder' }
  },
  {
    title: '导购/搭配师',
    dataIndex: 'fashionerName',
    align: 'center',
    width: '120px'
  },
  /* {
    title: '商品总数',
    dataIndex: 'allCount',
    align: 'center'
  },
  {
    title: '发货总数',
    dataIndex: 'sendCount',
    align: 'center'
  },
  {
    title: '购买总数',
    dataIndex: 'buyCount',
    align: 'center'
  }, */
  {
    title: '操作',
    dataIndex: 'action',
    width: '120px',
    align: 'center',
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  mixins: [globalMixin],
  components: {
    STable,
    LogisticsModal,
    Replenish,
    DeleteGoodsModal,
    ReturnGoodsModal,
    ReturnRecordModal,
    CancelModal,
    ForTestModal,
    StillGood,
    SpecifySettleModal,
    PayModal
  },
  data() {
    this.columns = columns
    return {
      userInfo: Vue.ls.get(USER_INFO),
      type: '',
      // statusList: [],
      actionList: [],
      isWarnList: [
        { value: 0, name: '无异常' },
        { value: 1, name: '还货预警' },
        { value: 2, name: '超时预警' }
      ],
      queryParam: {},
      paginationProps: {
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
      },
      loadData: async parameter => this.fetchTableList(parameter)
    }
  },
  watch: {
    $route(to, from) {
      console.log(to, from)
      let currentName = 'box-serviceOrder-list'
      let detailName = 'box-serviceOrder-detail'
      let printName = 'box-print'
      if (to.name.includes(currentName) && from.name.includes(detailName)) {
        let fromPathArr = from.path.split('/')
        // console.log(fromPathArr)
        this.fetchBoxByBoxId(fromPathArr[4]).then(res => {
          if (res.code == 0) {
            let url = window.location.pathname.split('/')
            if ((res.data.type == 10 && url.includes('fashioner')) || (res.data.type == 20 && url.includes('sales'))) {
              this.$refs.table.refresh()
            } else {
              // 修正搭配师详情页 直接跳转导购服务单列表
              this.getType()
              this.queryParam = {}
              this.$refs.table.refresh(true)
            }
          }
        })
      } else {
        if (to.name.includes(currentName) && !(from.name.includes(detailName) || from.name.includes(printName))) {
          this.getType()
          this.queryParam = {}
          this.$refs.table.refresh(true)
        } else if (from.name.includes(currentName) && to.name.includes(currentName)) {
          this.getType()
          this.queryParam = {}
          this.$refs.table.refresh(true)
        } else if (from.name.includes(currentName) && !(to.name.includes(detailName) || to.name.includes(printName))) {
          this.$destroy()
        }
      }
    }
  },
  filters: {
    filterStatus(v, statusList) {
      if (statusList.length > 0) {
        let result = statusList.filter(e => e.stateValue == v)
        if (result.length > 0) {
          return result[0].stateName
        } else {
          return v
        }
      } else {
        return v
      }
    },
    isWarn(v) {
      switch (v) {
        case 0:
          return ''
        case 1:
          return '还货预警'
        case 2:
          return '超时预警'
      }
    }
  },
  computed: {
    filterAction(name, status) {
      return (name, status) => {
        let result = this.actionList.filter(e => e.name == name)
        if (result[0].action.includes(status)) {
          return true
        } else {
          return false
        }
      }
    }
  },
  created() {
    this.getType()
    this.getStatus()
  },
  methods: {
    getStatus() {
      this.actionList = getOrderAction()
    },
    getType() {
      let url = window.location.pathname.split('/')
      if (url.includes('fashioner')) {
        this.type = 'fashioner'
      } else if (url.includes('sales')) {
        this.type = 'sales'
      }
    },
    // 重制
    reMake(record) {
      let params = {
        page: {
          pageNo: 1,
          pageSize: 10
        },
        requestData: {
          boxId: record.id
        },
        user_id: this.userInfo.id
      }
      resetAddCartByBoxId(params).then(res => {
        if (res.code === 0) {
          let information = {
            defLogistic: {
              province: res.data.logistics.province,
              city: res.data.logistics.city,
              district: res.data.logistics.district,
              address: res.data.logistics.address,
              contactName: res.data.logistics.name,
              contactPhone: res.data.logistics.phone,
              id: res.data.logistics.customerLogisticsId
            },
            pocketTelId: res.data.box.pocketTelId, // 布袋ID
            shopDiscount: res.data.box.shopDiscount // 折扣价格
          }

          localStorage.setItem('box_Information', JSON.stringify(information))
          let outNo = 'severstyle'
          this.$router.push(`/box/workbench/fashioner/collocation/${record.unionId}/${outNo}`)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 导出
    async confirm(e) {
      console.log(e)
    },
    cancel(e) {
      console.log(e)
    },
    // 创建时间
    onChange(value, dateString) {
      console.log('Selected Time: ', value)
      console.log('Formatted Selected Time: ', dateString)
    },
    onOk(value) {
      console.log('onOk: ', value)
    },
    // 搜索
    searchList(e) {
      this.$refs.table.refresh(true)
    },
    // 重置
    resetList() {
      this.queryParam = {}
      this.searchList()
    },
    // 列表数据
    async fetchTableList(parameter) {
      let data = await this.fetchData(parameter)
      if (data.data.length > 0) {
        let list = data.data.map(e => e.id)
        let result = await this.fetchCount(list)
        if (result.length > 0) {
          for (let item of data.data) {
            let reL = result.filter(e => e.boxId == item.id)
            if (reL.length > 0) {
              Object.assign(item, reL[0])
            }
          }
          // console.log(data)
        }
      }
      return data
    },
    fetchData(parameter) {
      // console.log(globalData)
      let params = {
        page: parameter,
        requestData: {
          type: this.type == 'fashioner' ? 10 : 20
        }
      }

      const queryParam = JSON.parse(JSON.stringify(this.queryParam))
      if (queryParam.status == 'null') {
        delete queryParam.status
      }
      if (queryParam.isWarn == 'null') {
        delete queryParam.isWarn
      }
      Object.assign(params.requestData, queryParam)
      delete params.requestData.regTime
      if (this.queryParam.regTime && this.queryParam.regTime.length > 0) {
        params.requestData.startTime = this.queryParam.regTime[0]
        params.requestData.endTime = this.queryParam.regTime[1]
      }
      if (this.queryParam.boxSn) {
        params.requestData.boxSn = this.queryParam.boxSn.trim()
      }
      if (this.queryParam.nickName) {
        params.requestData.nickName = this.queryParam.nickName.trim()
      }
      if (this.queryParam.expressNo) {
        params.requestData.expressNo = this.queryParam.expressNo.trim()
      }
      // console.log(params)
      return queryForList(params).then(res => {
        // console.log(res)
        if (res.code === 0) {
          const data = {
            page: res.page,
            data: res.data
          }

          return data
        } else {
          this.$message.error(res.msg)
          const data = {
            page: {
              pageNo: 0,
              count: 0,
              pageSize: 10
            },
            data: []
          }
          return data
        }
      })
    },
    fetchCount(list) {
      let params = {
        requestData: {
          boxIds: list
        }
      }
      return boxListCount(params).then(res => {
        if (res.code == 0) {
          return res.data
        } else {
          this.$message.error(res.msg)
          return []
        }
      })
    },
    fetchBoxByBoxId(id) {
      let params = {
        requestData: {
          boxId: id
        }
      }
      return new Promise((resolve, reject) => {
        getBoxByBoxId(params).then(res => {
          resolve(res)
        })
      })
    },
    showLogistics(record) {
      this.$refs.logisticsModal.show(record.id, record.unionId)
    },
    async showReplenish(record) {
      let result = await fetchUserIsBlack(record.unionId)
      if (result) {
        this.$message.warning('黑名单用户，无法补货!')
        return
      }
      let params = {
        requestData: {
          boxId: record.id
        }
      }
      getSupplyLogistics(params).then(res => {
        if (res.code == 0) {
          let data = res.data
          data = { ...data, name: res.data.logisticsName, customerLogisticsId: record.customerLogisticsId }
          this.$refs.replenish.show(record.id, record.unionId, data)
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    showDelete(record) {
      this.$refs.deleteGoods.show(record.id)
    },
    async showReturn(record) {
      let result = await this.checkUnSignProductList(record.id)
      if (result) {
        this.$refs.returnGoods.show(record.id, record.unionId, record.customerLogisticsId)
      }
    },
    checkUnSignProductList(id) {
      return checkUnSignProduct(id).then(res => {
        if (res.code == 0) {
          return true
        } else {
          this.$message.warning(res.msg)
          return false
        }
      })
    },
    showStill(record) {
      this.$refs.stillGood.showModel(record.id, record.unionId, record.customerLogisticsId)
    },
    showCancel(record) {
      this.$refs.cancelModal.show()
    },
    // showAbnormal(record) {
    //   this.$refs.returnRecord.show(record.id)
    // },
    showTestDeliver(record) {
      this.$refs.forTestModal.show('deliver', record.id, record.askId, record.boxSn)
    },
    showTestSign(record) {
      this.$refs.forTestModal.show('sign', record.id, record.askId, record.boxSn)
    },
    showTestDone(record) {
      this.$refs.forTestModal.show('done', record.id, record.askId, record.boxSn)
    },
    updateTable() {
      this.$refs.table.refresh()
    },
    showSpecifySettle(record) {
      this.$refs.specifySettleModal.show(record.id, record.explicitBrand)
    },
    showPay(record) {
      this.$refs.payModal.show(record.id)
    }
  }
}
</script>
<style scoped></style>

